import { ref } from 'vue'
import { useRoute, onBeforeRouteUpdate } from 'vue-router'
import { useCookies } from '@vueuse/integrations/useCookies';
import { router } from '~/router';

export function useTabList(){
  const route = useRoute()
  const cookie = useCookies()
  //const router = useRouter()

  const activeTab = ref(route.path)
  const tabList = ref([
    {
      title: "后台首页",
      path: "/",
    }
  ])

  //添加标签导航的方法
  function addTab(tab){
    let noTab = tabList.value.findIndex(t=>t.path == tab.path) == -1
    if(noTab){
      tabList.value.push(tab)
    }

    cookie.set("tabList",tabList.value)

  }

  //初始化标签导航列表
  function initTabList(){
    let tbs = cookie.get("tabList")
    if(tbs){
      tabList.value = tbs
    }
  }

  initTabList() //执行

  onBeforeRouteUpdate((to,from)=>{
    /* console.log({
      title:to.meta.title,
      path:to.path
    }); */
    activeTab.value = to.path  //标签导航处于激活状态
    //添加标签导航
    addTab({
      title:to.meta.title,
      path:to.path
    });
    
  })

  //标签导航栏切换时地址跟着换
  const changeTab = (t)=>{
    //console.log(t);
    activeTab.value = t
    router.push(t)
  }

  const removeTab = (t) => {
    //console.log(t)
    let tabs = tabList.value
    //console.log(tabs)
    let a = activeTab.value
    //console.log(a)
    if(a == t){
      tabs.forEach((tab,index)=>{
        if(tab.path == t){
          const nextTab = tabs[index+1] || tabs[index-1]
          //console.log(nextTab);
          if(nextTab){
            a = nextTab.path
            //console.log(a);
          }
        }
      })
    }
    //activeTab.value = a
    router.push(a) //我修改过的地方
    tabList.value = tabList.value.filter( tab=>tab.path != t )
    

    cookie.set("tabList",tabList.value)
  }

  const handelClose =(c) =>{
    //console.log(c);
    if(c=="clearAll"){
      //标签导航切换回首页
      activeTab.value='/'
      router.push('/') //我修改过的地方
      //过滤只剩下首页
      tabList.value =[
        {
          title: "后台首页",
          path: "/",
        }
      ]
    }else if(c=="clearOther"){
      //过滤只剩下首页和当前激活页
      tabList.value = tabList.value.filter(tab=>tab.path == '/' || tab.path == activeTab.value)
    }
    cookie.set("tabList",tabList.value)
  }

  return {
    activeTab,tabList,changeTab,removeTab,handelClose
  }

}